<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>流量统计系统</title>
    <style>
        :root {
            --primary-color: #4CAF50;
            --danger-color: #f44336;
        }

        body {
            margin: 0;
            padding: 0;
            background: transparent;
            -webkit-tap-highlight-color: transparent;
        }

        .container {
            width: 100%;
            padding: 20px;
            background: #fff;
            box-sizing: border-box;
        }

        .system-title {
            font-size: 28px;
            font-weight: 600;
            color: #2c3e50;
            margin: 0 0 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid var(--primary-color);
            text-align: center;
        }

        /* 流量显示容器 */
        .usage-container {
            display: flex;
            gap: 15px;
            margin-bottom: 25px;
            flex-wrap: wrap;
        }

        .usage-item {
            flex: 1;
            min-width: 200px;
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
            border-left: 4px solid;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }

        .usage-item.primary {
            border-color: var(--primary-color);
        }

        .usage-item.download {
            border-color: #2196F3;
        }

        .usage-item.upload {
            border-color: #4CAF50;
        }

        .usage-item svg {
            flex-shrink: 0;
        }

        .usage-text {
            line-height: 1.4;
        }

        .usage-text .label {
            font-size: 14px;
            color: #666;
        }

        .usage-text .value {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
        }

        /* 设置卡片 */
        .setting-card {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 6px;
            margin-bottom: 15px;
            border-left: 3px solid var(--primary-color);
        }

        .input-group {
            margin-top: 8px;
        }

        .input-label {
            display: block;
            font-size: 12px;
            color: #666;
            margin-bottom: 4px;
        }

        input[type="number"] {
            width: 160px;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        /* 开关样式 */
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 26px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }

        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 20px;
            width: 20px;
            left: 3px;
            bottom: 3px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        input:checked+.toggle-slider {
            background-color: var(--primary-color);
        }

        input:checked+.toggle-slider:before {
            transform: translateX(24px);
        }

        /* 按钮组 */
        .button-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 20px;
        }

        button {
            padding: 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            transition: filter 0.2s;
        }

        button:hover {
            filter: brightness(0.95);
        }

        button.save {
            background: var(--primary-color);
            color: white;
        }

        button.clear {
            background: var(--danger-color);
            color: white;
        }

        /* 说明区域 */
        .description {
            font-size: 12px;
            color: #666;
            line-height: 1.5;
            margin: 20px 0;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 6px;
            border-left: 3px solid var(--primary-color);
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- <h1 class="system-title">流量统计系统</h1> -->

        <div class="usage-container">
            <!-- 总流量 -->
            <div class="usage-item primary">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
                </svg>
                <div class="usage-text">
                    <div class="label">总流量</div>
                    <!-- <div class="value"><span id="currentUsage">0.000</span> GB</div> -->
                    <div class="value"><span id="currentUsage">0.000 KB</span></div>
                </div>
            </div>

            <!-- 下载流量 -->
            <div class="usage-item download">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/>
                </svg>
                <div class="usage-text">
                    <div class="label">下载流量</div>
                    <!-- <div class="value"><span id="currentRx">0.000</span> GB</div> -->
                    <div class="value"><span id="currentRx">0.000 KB</span></div>
                </div>
            </div>

            <!-- 上传流量 -->
            <div class="usage-item upload">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" transform="rotate(180 12 12)"/>
                </svg>
                <div class="usage-text">
                    <div class="label">上传流量</div>
                    <!-- <div class="value"><span id="currentTx">0.000</span> GB</div> -->
                    <div class="value"><span id="currentTx">0.000 KB</span></div>
                </div>
            </div>
        </div>

        <div class="setting-card">
            <div class="input-label">流量限制开关:</div>
            <label class="toggle-switch">
                <input type="checkbox" id="autoReset">
                <span class="toggle-slider"></span>
            </label>
        </div>

        <div class="setting-card">
            <div class="input-label">流量限制设置:</div>
            <div class="input-group">
                <input type="number" id="limit" min="1" step="1" placeholder="输入流量值">
                <span style="margin-left:8px;color:#666">GB</span>
            </div>
        </div>

        <div class="description">
            <strong>📋 使用说明</strong>
            <ul style="margin:10px 0 0;padding-left:20px">
                <li>流量限制设置当月自动断网门限值</li>
                <li>开启后当月总量达到门限时自动断网</li>
                <li>系统统计延迟可能导致少量误差（约几MB~上百MB）</li>
                <li>建议设置时保留适当余量</li>
            </ul>
        </div>

        <div class="button-group">
            <button class="save" onclick="saveConfig()">
                <svg viewBox="0 0 24 24" width="16" height="16">
                    <path fill="currentColor" d="M17 3H5c-1.1 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/>
                </svg>
                保存设置
            </button>
            <button class="clear" onclick="clearUsage()">
                <svg viewBox="0 0 24 24" width="16" height="16">
                    <path fill="currentColor" d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
                </svg>
                清除数据
            </button>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', async () => {
            // 初始化配置
            try {
                const configRes = await fetch('http://192.168.1.1:6789/api/get/set');
                if (configRes.ok) {
                    const config = await configRes.json();
                    if (config.switch === 1) {
                        const muchGB = (config.much / 1073741824).toFixed(3);
                        document.getElementById('autoReset').checked = true;
                        document.getElementById('limit').value = muchGB;
                        localStorage.setItem('dataLimit', muchGB);
                        localStorage.setItem('autoReset', 'true');
                    }
                }
            } catch (error) {
                console.log('使用本地存储配置');
            }

            // 初始化显示
            document.getElementById('autoReset').checked = localStorage.getItem('autoReset') === 'true';
            document.getElementById('limit').value = localStorage.getItem('dataLimit') || 10;

            // 开始轮询
            fetchData();
            setInterval(fetchData, 5000);
        });

        async function fetchData() {
            try {
                const response = await fetch('http://192.168.1.1:6789/api/get/Total');
                if (!response.ok) return;
                
                const data = await response.json();
                document.getElementById('currentUsage').textContent = data.total;
                document.getElementById('currentRx').textContent = data.rx;
                document.getElementById('currentTx').textContent = data.tx;
                // document.getElementById('currentUsage').textContent = (data.total / 1073741824).toFixed(3);
                // document.getElementById('currentRx').textContent = (data.rx / 1073741824).toFixed(3);
                // document.getElementById('currentTx').textContent = (data.tx / 1073741824).toFixed(3);
                
                localStorage.setItem('dataUsage', data.total / 1073741824);
            } catch (error) {
                console.error('数据获取失败:', error);
            }
        }

        function saveConfig() {
            const switchValue = document.getElementById('autoReset').checked ? 1 : 0;
            const gbValue = parseFloat(document.getElementById('limit').value);

            if (switchValue && (isNaN(gbValue) || gbValue <= 0)) {
                showAlert('⚠️ 请输入有效的流量限制值', '#f44336');
                return;
            }

            const muchValue = Math.round(gbValue * 1073741824);
            fetch(`http://192.168.1.1:6789/api/set/total?switch=${switchValue}&much=${muchValue}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAlert('✅ 设置保存成功', '#4CAF50');
                        localStorage.setItem('dataLimit', gbValue);
                        localStorage.setItem('autoReset', switchValue === 1);
                    } else {
                        showAlert(`⚠️ 保存失败：${data.msg || '未知错误'}`, '#f44336');
                    }
                })
                .catch(error => {
                    console.error('保存失败:', error);
                    showAlert('⚠️ 网络请求异常', '#f44336');
                });
        }

        function clearUsage() {
            showConfirm(
                '确认清除流量数据',
                '此操作将永久重置所有使用记录！清除后需要5分钟才能重新显示统计，期间流量仍会被记录。',
                () => {
                    fetch('http://192.168.1.1:6789/api/set/total')
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                showAlert('♻️ 数据已重置', '#4CAF50');
                                fetchData();
                            } else {
                                showAlert(`⚠️ 清除失败：${data.msg || '未知错误'}`, '#f44336');
                            }
                        })
                        .catch(error => {
                            console.error('清除失败:', error);
                            showAlert('⚠️ 网络请求异常', '#f44336');
                        });
                }
            );
        }

        // 弹窗系统
        function showAlert(text, color) {
            const alert = document.createElement('div');
            alert.style.cssText = `
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                padding: 12px 24px;
                background: ${color};
                color: white;
                border-radius: 6px;
                box-shadow: 0 3px 10px rgba(0,0,0,0.2);
                z-index: 1000;
                animation: alertSlide 0.3s ease-out;
            `;
            alert.textContent = text;
            document.body.appendChild(alert);
            setTimeout(() => alert.remove(), 1500);
        }

        function showConfirm(title, text, callback) {
            const overlay = document.createElement('div');
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.3);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 999;
            `;

            const box = document.createElement('div');
            box.style.cssText = `
                background: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: 0 5px 20px rgba(0,0,0,0.2);
                width: 300px;
            `;

            box.innerHTML = `
                <h3 style="margin:0 0 15px;color:#333">${title}</h3>
                <p style="color:#666;margin-bottom:20px">${text}</p>
                <div style="display:flex;gap:10px;justify-content: flex-end">
                    <button id="confirmCancel" style="padding:8px 20px;background:#6c757d;color:white;border:none;border-radius:4px;cursor:pointer">取消</button>
                    <button id="confirmOK" style="padding:8px 20px;background:#4CAF50;color:white;border:none;border-radius:4px;cursor:pointer">确认</button>
                </div>
            `;

            box.querySelector('#confirmOK').addEventListener('click', () => {
                overlay.remove();
                callback();
            });
            box.querySelector('#confirmCancel').addEventListener('click', () => overlay.remove());

            overlay.appendChild(box);
            document.body.appendChild(overlay);
        }
    </script>
</body>

</html>